<template>
    <!-- 组件包装 -->
    <component
        :is="cmpMap[cmp.code]"
        :class="cmp.class"
        :style="style"
        :config="cmp.config"
        :inEditor="true"
        v-if="designing"
        v-drag="{ cmp, setCurrent: selectCmp, justify: true, callback: (val) => setCmpStyle(cmp, val) }"
    ></component>
    <component v-else :is="cmpMap[cmp.code]" :class="cmp.class" :style="cmp.style" :config="cmp.config" />
</template>
<script setup>
import * as _ from "lodash";

const { cmp, designing, inEditor } = defineProps({
    cmp: Object,
    designing: { type: Boolean, default: true },
});
const emits = defineEmits(["select", "change"]);
const style = computed(() => {
    let style = cmp.style;
    let result = {};
    // 为空的字段需要移除
    if (style) {
        for (var i in style) {
            let val = style[i];
            if (!val && val != 0) {
                continue;
            }
            if (val == "") {
                continue;
            }
            result[i] = val;
        }
    }
    return result;
});

// 加载组件列表
let files = import.meta.glob("./cmps/*.*", { eager: true });
let cmpMap = {};
_.forEach(files, (v, k) => {
    k = k.replace("./cmps/", "").replace(".vue", "").replace(".js", "");
    cmpMap[k] = v.default;
});

function selectCmp(cmp) {
    emits("select", cmp);
}

function setCmpStyle(cmp, val) {
    cmp.style = {
        ...cmp.style,
        ...val,
    };
    emits("change");
}
</script>

<style lang="scss" scoped></style>
